package com.firefly.service.command.common;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @description: 验证码生成、校验
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2023/2/9
 **/
@Component
@Slf4j
public class AliyunCodeCommand {
    @Value("${aliyun.accesskeyid}")
    private String accessKeyId;
    @Value("${aliyun.secret}")
    private String secret;
    @Value("${aliyun.dysms.regionid}")
    private String regionId;
    @Value("${aliyun.dysms.signname}")
    private String signName;
    @Value("${aliyun.dysms.template-code}")
    private String templateCode;
    public Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(secret);
        // 访问的域名
        config.setEndpoint(regionId);
        return new Client(config);
    }

    public SendSmsResponse sendSms(String phone) throws Exception {
        Client client = this.createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\"1234\"}");
                /*.setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\"1234\"}");*/
        RuntimeOptions runtime = new RuntimeOptions();
        SendSmsResponse response = null;
        try {
            // 复制代码运行请自行打印 API 的返回值
            response = client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return response;
    }
}
